package com.ruoyi.project.module.ordersHead.controller;

import java.io.*;
import java.util.*;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.utils.UserUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.module.ordersDetail.service.IOrdersDetailService;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.project.module.ordersHead.domain.OrdersHead;
import com.ruoyi.project.module.ordersHead.service.IOrdersHeadService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 上传的订单 信息操作处理
 *
 * @author lcx
 * @date 2018-08-18
 */
@Controller
@RequestMapping("/module/ordersHead")
public class OrdersHeadController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(OrdersHeadController.class);
    private String prefix = "module/ordersHead";

    @Autowired
    private IOrdersHeadService ordersHeadService;
    @Autowired
    private IOrdersDetailService iOrdersDetailService;
    @Autowired
    private IDeptService IDeptService;

    @RequiresPermissions("module:ordersHead:view")
    @GetMapping()
    public String ordersHead() {
        return prefix + "/ordersHead";
    }



/*    *//*获取短信验证码*//*
    @RequestMapping("/wxYanzhengma")
    public void yanzheng(HttpServletResponse response, String tel, HttpServletRequest request) throws ClientException {
        HttpSession session = request.getSession();
        String code = SmsUtil.getCode();
        String type = (String) session.getAttribute("type");
//        if ("2".equals(type)||"3".equals(type)||"4".equals(type)||"5".equals(type)) {
        SendSmsResponse sendSmsResponse = SmsUpdatePassword.sendSms(tel, code);
        session.setAttribute("code", code);
        System.out.println(code);
//        }
    }*/


    /**
     * 查询上传的订单列表
     */
    @RequiresPermissions("module:ordersHead:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrdersHead ordersHead) {
        startPageChange();
        ordersHead.setCompanyID(UserUtils.getDepId());
        //根据公司id查询所有上传订单
        List<OrdersHead> list = ordersHeadService.selectOrdersHeadList(ordersHead);
        for (OrdersHead oh : list){
            String fileLink = "<a href=\"javascript:;\" data-text=\""+oh.getFileUrl()+"\" class=\"down\">"+oh.getFileName()+"</a>";
            oh.setFileName(fileLink);
        }

        List<OrdersHead> sumCountList = ordersHeadService.selectSumCountOrdersHeadList(ordersHead);

        return getDataTableAsSum(list, sumCountList);
    }

    /**
     * 新增上传的订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增上传的订单
     */
    @GetMapping("/uploadOrder")
    public String uploadOrder() {
        return prefix + "/uploadOrder";
    }

    /**
     * 新增保存上传的订单
     */
    @RequiresPermissions("module:ordersHead:add")
    @Log(title = "上传的订单", action = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(OrdersHead ordersHead) {
        //return toAjax(ordersHeadService.insertOrdersHead(ordersHead));
        return error();
    }

    /**
     * 新增保存上传的订单
     */
    @RequiresPermissions("module:ordersHead:add")
    @Log(title = "上传的订单", action = BusinessType.INSERT)
    @PostMapping("/uploadOrder")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("list") String jsonList, String bz) {
        User user = ShiroUtils.getUser();
        int result = 0;
        try{
             result = ordersHeadService.insertHeadAndDetail(jsonList, bz, user);
        }catch (FileNotFoundException e){
            return AjaxResult.error("没有找到文件或excel列长度不正确");
        }catch (IOException e1){
            return AjaxResult.error(e1.getMessage());
        }
        catch (Exception e2){//列长度不正确，空文件
            return AjaxResult.error("没有找到文件或excel列长度不正确。");
        }

        return toAjax(result);
    }

    /**
     * 修改上传的订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        OrdersHead ordersHead = ordersHeadService.selectOrdersHeadById(id);
        mmap.put("ordersHead", ordersHead);
        return prefix + "/edit";
    }

    /**
     * 修改保存上传的订单
     */
    @RequiresPermissions("module:ordersHead:edit")
    @Log(title = "上传的订单", action = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(OrdersHead ordersHead) {
        return toAjax(ordersHeadService.updateOrdersHead(ordersHead));
    }

    /**
     * 删除上传的订单
     */
    @RequiresPermissions("module:ordersHead:remove")
    @Log(title = "上传的订单", action = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ordersHeadService.deleteOrdersHeadByIds(ids));
    }

    @Log(title = "订单上传", action = BusinessType.IMPORT)
    @PostMapping("/FileUploadServlet")
    @ResponseBody
    public AjaxResult updateExcle(User user, @RequestParam("exclefile") MultipartFile file, HttpServletRequest request) {

        try {
            String fileName = file.getOriginalFilename();
            String[] splitResult = fileName.split("\\.");
            String extension = "." + splitResult[splitResult.length - 1];
            if (!extension.equalsIgnoreCase(".xls") && !extension.equalsIgnoreCase(".xlsx")) {
                return error();
            }
            System.out.println(file.isEmpty());
            if (!file.isEmpty()) {
                String path = FileUploadUtils.uploadCommon(RuoYiConfig.getProfile(), "order", file);
                return fileUrl(fileName, path);
            }
//            return error();
            String path = FileUploadUtils.uploadCommon(RuoYiConfig.getProfile(), "order", file);
            return fileUrl(fileName, path);
        } catch (Exception e) {
            //log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }

    @Log(title = "订单下载", action = BusinessType.EXPORT)
    @PostMapping("/down")
    @ResponseBody
    public void downFile(HttpServletResponse response, String fileUrl){
        try {
            FileUtils.downFile(response, fileUrl);
        }catch (FileNotFoundException e){
            log.error(e.toString());
        }catch (IOException e1){
            log.error(e1.toString());
        }catch (Exception e2){
            log.error(e2.toString());
        }
    }


    /*获取验证码*/
    @RequestMapping("/wxYanzhengma")
    public void yanzheng(HttpServletResponse response, String tel, HttpServletRequest request) throws ClientException {
//        HttpSession session = request.getSession();
//        String code = SmsUtil.getCode();
//        SendSmsResponse sendSmsResponse = SmsUpdatePassword.sendSms("17770084150","1000");
//        session.setAttribute("code", code);
//        System.out.println(code);
//        }
    }

}
